package com.ztesoft.book.core.sys.sysuserrole.service.impl;

import com.ztesoft.book.common.utils.base.SnowFlakeGenerator;
import com.ztesoft.book.core.base.base.service.impl.BaseExServiceImpl;
import com.ztesoft.book.core.sys.sysuserrole.dto.SysUserRoleDTO;
import com.ztesoft.book.core.sys.sysuserrole.mapper.SysUserRoleMapper;
import com.ztesoft.book.core.sys.sysuserrole.qo.SysUserRoleQO;
import com.ztesoft.book.core.sys.sysuserrole.service.SysUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @Description 用户与角色对应关系
 * @Author YangFan
 * @Date 2021-06-22 17:32
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends BaseExServiceImpl<SysUserRoleMapper, SysUserRoleDTO, SysUserRoleQO> implements SysUserRoleService {


    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<SysUserRoleDTO> getListByUserIds(Set<String> userIdSet) {

        if (userIdSet == null || userIdSet.isEmpty()) {
            return new ArrayList<>();
        }
        return this.getMapper().getListByUserIds(userIdSet);


    }

    @Override
    public void save(String userId, List<String> roleIdList) {
        if (roleIdList == null || roleIdList.isEmpty()) {
            return;
        }
        //新增列表
        List<SysUserRoleDTO> addList = new ArrayList<>();
        //临时对象
        SysUserRoleDTO tempSysUserRoleDTO;

        for (String roleId : roleIdList) {
            tempSysUserRoleDTO = new SysUserRoleDTO();
            tempSysUserRoleDTO.setId(SnowFlakeGenerator.generateIdStr());
            tempSysUserRoleDTO.setUserId(userId);
            tempSysUserRoleDTO.setRoleId(roleId);
            addList.add(tempSysUserRoleDTO);
        }
        //批量保存。
        sysUserRoleMapper.saveBatch(addList);
    }

    @Override
    public void deleteByUserId(String userId) {
        sysUserRoleMapper.deleteByUserId(userId);
    }

    @Override
    public List<String> getRoleIdListByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return new ArrayList<>();
        }
        return this.getMapper().getRoleIdListByUserId(userId);


    }

    @Override
    protected SysUserRoleMapper getMapper() {
        return sysUserRoleMapper;
    }


    /**
     * 统计角色现有用户数
     *
     * @param roleId roleId
     * @return
     */
    @Override
    public int countRoleUser(String roleId) {
        return sysUserRoleMapper.countRoleUser(roleId);
    }
}
